from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File
from sqlalchemy.orm import Session
from typing import Optional
import math

from app.core.database import get_db
from app.crud.news import news_crud
from app.schemas.news import NewsCreate, NewsUpdate, NewsResponse, NewsListResponse
from app.api.deps import get_current_user, get_current_admin_user
from app.models.user import User
from app.services.tencent.cos_service import TencentCOSService
from app.services.image.processor import ImageProcessor

router = APIRouter()

# 依赖注入
def get_cos_service() -> TencentCOSService:
    return TencentCOSService()

def get_image_processor() -> ImageProcessor:
    return ImageProcessor()

# 新闻图片上传接口 - 需要管理员权限
@router.post("/news/upload-image", summary="上传新闻图片", description="专门用于新闻的图片上传接口（需要管理员权限）")
async def upload_news_image(
    file: UploadFile = File(...),
    cos_service: TencentCOSService = Depends(get_cos_service),
    processor: ImageProcessor = Depends(get_image_processor),
    current_admin: User = Depends(get_current_admin_user)
):
    """上传新闻图片到COS存储 - 需要管理员权限"""
    try:
        # 读取文件内容
        contents = await file.read()
        
        # 验证图片格式
        if not processor.validate_image_format(contents):
            raise HTTPException(status_code=400, detail="不支持的图片格式")
        
        # 安全地获取文件扩展名
        if file.filename and '.' in file.filename:
            file_extension = file.filename.split('.')[-1].lower()
        else:
            file_extension = 'jpg'  # 默认扩展名
        
        # 上传到COS，使用news文件夹
        upload_result = cos_service.upload_image(
            image_data=contents,
            file_extension=file_extension,
            folder='news'  # 专门的新闻图片文件夹
        )
        
        if upload_result['success']:
            return {
                "success": True,
                "message": "新闻图片上传成功",
                "url": upload_result['url'],
                "filename": upload_result['file_name']
            }
        else:
            raise HTTPException(status_code=500, detail=f"图片上传失败: {upload_result['error']}")
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")

@router.post("/news", response_model=NewsResponse, summary="创建新闻", description="发布新的新闻内容（需要管理员权限）")
def create_news(
    news_data: NewsCreate,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_user)
):
    """创建新闻 - 发布新的新闻内容（需要管理员权限）"""
    return news_crud.create_news(db, news_data, current_admin.id)

@router.get("/news", response_model=NewsListResponse, summary="获取新闻列表", description="分页查询新闻，支持关键词搜索")
def get_news_list(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    size: int = Query(10, ge=1, le=100, description="每页数量，最大100"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """获取新闻列表 - 分页查询新闻，支持关键词搜索"""
    skip = (page - 1) * size
    news_list, total = news_crud.get_news_list(db, skip=skip, limit=size, keyword=keyword)
    
    return NewsListResponse(
        items=news_list,
        total=total,
        page=page,
        size=size,
        pages=math.ceil(total / size)
    )

@router.get("/news/{news_id}", response_model=NewsResponse, summary="获取新闻详情", description="根据ID查看具体新闻内容")
def get_news_detail(
    news_id: int,
    db: Session = Depends(get_db)
):
    """获取新闻详情 - 根据ID查看具体新闻内容"""
    news = news_crud.get_news_by_id(db, news_id)
    if not news:
        raise HTTPException(status_code=404, detail="新闻不存在")
    return news

@router.put("/news/{news_id}", response_model=NewsResponse, summary="更新新闻", description="修改已有新闻内容（需要管理员权限）")
def update_news(
    news_id: int,
    news_data: NewsUpdate,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_user)
):
    """更新新闻 - 修改已有新闻内容（需要管理员权限）"""
    news = news_crud.update_news(db, news_id, news_data)
    if not news:
        raise HTTPException(status_code=404, detail="新闻不存在")
    return news

@router.delete("/news/{news_id}", summary="删除新闻", description="移除指定新闻（需要管理员权限）")
def delete_news(
    news_id: int,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_user)
):
    """删除新闻 - 移除指定新闻（需要管理员权限）"""
    success = news_crud.delete_news(db, news_id)
    if not success:
        raise HTTPException(status_code=404, detail="新闻不存在")
    return {"message": "删除成功"}